package com.jhws.business.local.service;

import com.alibaba.fastjson.JSON;
import com.jhws.business.local.bo.LocalConstant;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.core.db.BaseDao;
import com.jhws.sys.appUser.bo.TblSipAcountDimBo;
import com.jhws.util.net.JhHttpClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class SipAcountSynchService {
    @Resource
    private BaseDao BaseDao;

    public void saveSipAcount(TblSipAcountDimBo sipAcountDimBo) {
        sipAcountDimBo.setIsSynch(LocalConstant.SYNCH_STATE_YES);
        BaseDao.saveOrUpdate(sipAcountDimBo);
    }

    public void deleteSipAcount(TblSipAcountDimBo sipAcountDimBo) throws Exception {
        BaseDao.delete(sipAcountDimBo);
    }

    public List<TblSipAcountDimBo> findTblSipAcountWhere(String whereStr) throws Exception {
        return BaseDao.findList("from TblSipAcountDimBo " + whereStr);
    }

    public boolean isUserExist(String username) {
        // TODO Auto-generated method stub
        try {
            String where = "where username = '" + username + "'";
            List<TblSipAcountDimBo> list = findTblSipAcountWhere(where);
            if (list.size() != 0)
                return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    public void mergeSipAcount(String serverUrl, Map<String, String> headers) throws Exception {
        List<TblSipAcountDimBo> list = findTblSipAcountWhere("where is_synch != '" + LocalConstant.SYNCH_STATE_YES + "'");
        if (list == null || list.isEmpty()) {
            return;
        }
        JhHttpClient hp = new JhHttpClient();
        for (TblSipAcountDimBo sipAcountDimBo : list) {
            String s = hp.postJson(serverUrl + "api/localSynch/sipAcount/acounts", JSON.toJSONString(sipAcountDimBo), headers);
            try {
                JsonRespData respData = JSON.parseObject(s, JsonRespData.class);
                if (respData.ret_code > 0) {
                    if (sipAcountDimBo.getIsSynch() == LocalConstant.SYNCH_STATE_NO) {
                        saveSipAcount(sipAcountDimBo);
                    } else if (sipAcountDimBo.getIsSynch() == LocalConstant.SYNCH_STATE_DEL) {
                        deleteSipAcount(sipAcountDimBo);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
